<template>
	<div>
		<h1>{{ username }}</h1>
		<img :src="avatar" alt="Avatar">
		<div v-for="comment in comments" :key="comment.comment_id">
			<p>Title: {{ comment.title }}</p>
			<p>Comment: {{ comment.comment }}</p>
			<button @click="deleteComment(comment.comment_id)">删除</button>
			<hr> <!-- 分隔线 -->
		</div>
	</div>
</template>

<script>
	import { useUsersStore } from '@/store/user.js';
	import axios from "axios";

	export default {
		data() {
			return {
				avatar: "",
				username: "",
				comments: []
			};
		},
		computed: {
			usersStore() {
				return useUsersStore();
			}
		},
		created() {
			this.fetchUserInfo();
			this.fetchComments();
		},
		methods: {
			fetchUserInfo() {
				const userStore = useUsersStore();
				this.username = userStore.name;
				this.avatar = userStore.avatar;
			},
			fetchComments() {
				const myUser = JSON.parse(localStorage.getItem('my_user'));
				const userId = myUser.name;
				const token = myUser.token;
				if (localStorage.hasOwnProperty("my_user") && myUser.token) {
					axios.defaults.headers.common["token"] = token;
					console.log(myUser.token); //Authorization
				}
				console.log("这个是用户id",userId)
				axios.get(`http://127.0.0.1:8080/v1/user?my_user=${userId}`)

				
						.then(response => {
							this.comments = response.data.data;
							console.log(response.data.data)
						})
						.catch(error => {
							console.error("Failed to fetch comments", error);
						});
			},
			deleteComment(commentId) {
				  const myUser = JSON.parse(localStorage.getItem('my_user'));
				  const userId = myUser.name;
				  const token = myUser.token;
				  
				  if (localStorage.hasOwnProperty("my_user") && myUser.token) {
				    axios.defaults.headers.common["token"] = token;
				    console.log(myUser.token); // Authorization
				  }
				  
				  console.log("这个是用户id", userId);
				  
				  axios
					.delete(`http://127.0.0.1:8080/v1/user?comment_id=${commentId}`)
					.then(response => {
					    if (response.data.code === 0) {
					      console.log("删除成功");
						  this.comments = this.comments.filter(comment => comment.comment_id !== commentId);
					    } else {
					      console.error("删除评论失败:", response.data.message);
						  
					    }
					  })
					.catch(error => {
					  console.error("删除评论请求失败", error);
					});

			}
		}
	};
</script>